package com.turtle.learning.users.rocketmq;

import com.turtle.learning.users.dto.UserAddBonusMsgDTO;
import com.turtle.learning.users.entity.BonusEventLog;
import com.turtle.learning.users.entity.User;
import com.turtle.learning.users.mapper.BonusEventLogMapper;
import com.turtle.learning.users.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 分享审核消费者
 *
 * @author turtle
 * @since 2020-05-06
 */
@Service
@Slf4j
@RocketMQMessageListener(consumerGroup = "customer-group", topic = "audit-topic")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShareAuditListener implements RocketMQListener<UserAddBonusMsgDTO> {

    private final UserMapper userMapper;
    private final BonusEventLogMapper bonusEventLogMapper;

    @Override
    public void onMessage(UserAddBonusMsgDTO userAddBonusMsgDTO) {
        // 给对应的用户添加积分
        User user = userMapper.selectById(userAddBonusMsgDTO.getUserId());
        user.setBonus(user.getBonus() + userAddBonusMsgDTO.getBonus());
        userMapper.updateById(user);
        // 新增积分变动日志
        BonusEventLog bonusEventLog = BonusEventLog.builder()
            .userId(user.getId())
            .value(userAddBonusMsgDTO.getBonus())
            .event("文章审核")
            .description("文章审核通过增加积分")
            .build();
        bonusEventLogMapper.insert(bonusEventLog);
        log.info("文章审核成功用户添加积分");
    }
}
